﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.LIB;
using YArchitech.Revit;
using SystemDiagramNew.TypeDefinition;

namespace SystemDiagramNew
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdSetPipeElevation : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			if (cmdData == null)
			{
				throw new System.ArgumentNullException("ExternalCommandData", "ExternalCommandData is null!");
			}
			this.uiApp = cmdData.Application;
			this.doc = this.uiApp.ActiveUIDocument.Document;
			this.sel = this.uiApp.ActiveUIDocument.Selection;
			RevitVersionFuncs.ClearSelection(this.sel);
			List<ViewType> list = new List<ViewType>();
            list.Add((ViewType)10);
			if (!YJKRevitTools.ViewCheck(this.uiApp.ActiveUIDocument, list))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			if (CmdSetPipeElevation.hWndRevit == null)
			{
				Process currentProcess = Process.GetCurrentProcess();
				IntPtr mainWindowHandle = currentProcess.MainWindowHandle;
				CmdSetPipeElevation.hWndRevit = new YJKWindowHandle(mainWindowHandle);
			}
			SetPipeElevation setPipeElevation = new SetPipeElevation();
			setPipeElevation.Show(CmdSetPipeElevation.hWndRevit);
			int wMsg = 7;
			CmdSetPipeElevation.SendMessage(CmdSetPipeElevation.hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			Transaction transaction = null;
			Reference reference = null;
			bool underPipe = true;
			for (;;)
			{
				transaction = new Transaction(this.doc, "标注标高");
				transaction.Start();
				try
				{
					switch (setPipeElevation.labelLocation)
					{
					case ElevationLabelLocation.OuterPipe:
						reference = this.SelectMarkPosition("请选择系统图管道（靠近标注端）", ref underPipe);
						break;
					case ElevationLabelLocation.InnerPipe:
						reference = this.SelectMarkPosition("请选择系统图管道", ref underPipe);
						break;
					}
					if (reference != null)
					{
						SetElevation setElevation = new SetElevation(cmdData, reference);
						setElevation.Execute(underPipe, setPipeElevation.precisionValue.SelectedIndex, setPipeElevation.customElevationText.Checked, setPipeElevation.deleteOldGroups.Checked, setPipeElevation.prefixValue.Text, setPipeElevation.customElevationValue.Text, setPipeElevation.labelLocation);
						transaction.Commit();
					}
					continue;
				}
				catch (Autodesk.Revit.Exceptions.OperationCanceledException ex)
				{
					ex.ToString();
					if (transaction != null)
					{
						TransactionStatus status = transaction.GetStatus();
                        if ((int)status == 1)
						{
							transaction.RollBack();
						}
                        else if ((int)status == 5)
						{
							transaction.RollBack();
						}
					}
					if (setPipeElevation.isPicking)
					{
						setPipeElevation.isPicking = false;
						continue;
					}
				}
				catch (Exception ex2)
				{
					ex2.ToString();
					if (transaction != null)
					{
						TransactionStatus status2 = transaction.GetStatus();
                        if ((int)status2 == 1)
						{
							transaction.RollBack();
						}
                        else if ((int)status2 == 5)
						{
							transaction.RollBack();
						}
					}
					continue;
				}
				break;
			}
			setPipeElevation.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		protected Reference SelectMarkPosition(string prompt, ref bool IsUnderPipe)
		{
			PipeDeailLineFilter pipeDeailLineFilter = new PipeDeailLineFilter(this.doc);
			Reference reference = this.sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, pipeDeailLineFilter, prompt);
			if (reference != null)
			{
				XYZ xyz = this.sel.PickPoint("请选择管道相对标注位置");
				if (xyz != null)
				{
					Element element = this.doc.GetElement(reference);
					Line curve = (element as DetailLine).GeometryCurve as Line;
					XYZ xyz2 = curve.GetEndPoint(0);
					XYZ xyz3 = curve.GetEndPoint(1);
					if (xyz2.X > xyz3.X)
					{
						XYZ xyz4 = xyz2;
						xyz2 = xyz3;
						xyz3 = xyz4;
					}
					if (Geometry.IsEqual(xyz2.X, xyz3.X) && Geometry.GreaterThan(xyz2.Y, xyz3.Y))
					{
						XYZ xyz5 = xyz2;
						xyz2 = xyz3;
						xyz3 = xyz5;
					}
					IsUnderPipe = (Geometry.PointAtLineLeft(xyz, xyz2, xyz3) || Geometry.Is_Point_OnSegment(xyz2, xyz3, xyz));
				}
			}
			return reference;
		}

		protected UIApplication uiApp;

		protected Document doc;

		protected Selection sel;

		public static YJKWindowHandle hWndRevit;
	}
}
